<template>
  <div id="intfconfig">
    <Splitpanes style="height: 100%">
      <Pane size="100">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input
              clearable
              placeholder="关键字查询"
              v-model="keywords"
              @keyup="keyup"
              type="search"
            ></vxe-input>
            <vxe-button
              type="text"
              status="primary"
              icon="vxe-icon-refresh"
              content="刷新"
              @click="handleSearch"
            ></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="modulTable">
          <vxe-table
            ref="moduleTable"
            v-loading="loading"
            :loading="loading"
            :height="conHeight - 150 + 'px'"
            border
            :data="intfMainList"
            @current-change="moduleRowClick"
            :row-config="{ isCurrent: true, isHover: true }"
            :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }"
            @cell-dblclick="editRow"
            :edit-rules="formRule"
            resizable
            show-overflow
            keep-source
          >
            <vxe-column type="checkbox" width="26" align="center"></vxe-column>
            <vxe-column type="seq" title="序号" width="30" align="center"></vxe-column>
            <vxe-column
              field="code"
              title="日志编号"
              width="100"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.code"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
            <vxe-column
              field="name"
              title="日志内容"
              min-width="120px"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.name"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
            <vxe-column
              field="pname"
              title="类型"
              width="100"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.pname"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
            <vxe-column
              field="sn"
              title="时间"
              width="100"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.sn"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
            <vxe-column
              field="state"
              title="标识"
              width="100"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.state"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { ElMessage } from 'element-plus';
// import { fa } from 'element-plus/es/locale';
import { VXETable } from 'vxe-table';
import { VxeMessage } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
// import saveAs from 'file-saver';
import { defineProps } from 'vue';
let props = defineProps<{
  pid: string;
  pname: string;
}>();
let store = AppStore();
let { proxy }: any = getCurrentInstance();
let modulePoitPre = reactive([]);
// 当前屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
let leftpane = ref('100');
let rightpane = ref('0');
//关键字
let keywords = ref('');
let loading = ref(false);
// 接口表格数据
let intfMainList = reactive([]);
let maindialogVisible = ref(false);
let mainform = reactive({
  id: '',
  code: '', //编码
  name: '', //名称
  pname: '', //所属模块
  type: '', //类型 数据库/服务
  state: 'new', //状态 禁用/调试/启用
  sn: intfMainList.length + 1, //排序号
  //数据库
  dbtype: '', //数据库类型
  dbaddr: '', //数据库地址
  dbname: '', //数据库名称
  dbusername: '', //账号
  dbpassword: '', //密码
  //服务
  servetype: '', //服务类型
  serveaddr: '' //服务地址
});

onMounted(() => {
  handleSearch();
});

// 点击刷新
function handleSearch() {
  loading.value = true;
  intfMainList.length = 0;
  let str = localStorage.getItem('intfItemLog');
  if (str) {
    intfMainList.push(...JSON.parse(str));
  }

  setTimeout(() => {
    loading.value = false;
  }, 500);
}
//新建
async function handleAdd() {
  clearmainform();
  maindialogVisible.value = true;
  // intfMainList.push(record);
}
async function saveRow() {
  if (!mainform.id) {
    mainform.id = '2000' + mainform.sn;
    intfMainList.push(mainform);
  } else {
    for (let i = intfMainList.length - 1; i >= 0; i--) {
      if (mainform.id == intfMainList[i].id) {
        setvalue(intfMainList[i], mainform);
        break;
      }
    }
  }
  localStorage.setItem('intfItemLog', JSON.stringify(intfMainList));
  VXETable.modal.message({ content: '操作成功', status: 'success' });
  maindialogVisible.value = false;
  setTimeout(() => {
    handleSearch();
  }, 500);
}
async function editRow({ row }) {
  clearmainform();
  setvalue(mainform, row);
  maindialogVisible.value = true;
}
function setvalue(form,row) {
    form.id = row.id;
  (form.code = row.code), //编码
    (form.name = row.name), //名称
    (form.pname = row.pname), //所属模块
    (form.type = row.type), //类型 数据库/服务
    (form.state = row.state), //状态 禁用/调试/启用
    (form.sn = row.sn), //排序号
    //数据库
    (form.dbtype = row.dbtype), //数据库类型
    (form.dbaddr = row.dbaddr), //数据库地址
    (form.dbname = row.dbname), //数据库名称
    (form.dbusername = row.dbusername), //账号
    (form.dbpassword = row.dbpassword), //密码
    //服务
    (form.servetype = row.servetype), //服务类型
    (form.serveaddr = row.serveaddr); //服务地址
}
function clearmainform() {
  mainform.id = '';
  (mainform.code = ''), //编码
    (mainform.name = ''), //名称
    (mainform.pname = props.pname), //所属模块
    (mainform.type = ''), //类型 数据库/服务
    (mainform.state = '新建'), //状态 禁用/调试/启用
    (mainform.sn = intfMainList.length + 1), //排序号
    //数据库
    (mainform.dbtype = ''), //数据库类型
    (mainform.dbaddr = ''), //数据库地址
    (mainform.dbname = ''), //数据库名称
    (mainform.dbusername = ''), //账号
    (mainform.dbpassword = ''), //密码
    //服务
    (mainform.servetype = ''), //服务类型
    (mainform.serveaddr = ''); //服务地址
}
// 点击修改保存
async function saveList() {
  // 获取表格实例
  let $Xtable = proxy.$refs.moduleTable;

  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    // const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
    //   return m.id === '';
    // });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = intfMainList.filter(e => {
      return e.id === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach(e => {
      let moduleAddParam = e;
    });

    // 新增
    InsertRecords.forEach(e => {
      const moduleAddParam = e;
      moduleAddParam.id = '1';
    });
    // localStorage.setItem('activeIndex', JSON.parse(JSON.stringify(this.intfMainList)));
    localStorage.setItem('intfItemLog', JSON.stringify(intfMainList));
    VXETable.modal.message({ content: '操作成功', status: 'success' });
    setTimeout(() => {
      handleSearch();
    }, 500);
  } else {
    return;
  }
}
// 点击删除
async function handleDelete() {
  let $Xtable = proxy.$refs.moduleTable;
  let selectRows = $Xtable.getCheckboxRecords();
  if (selectRows <= 0) {
    VXETable.modal.message({ content: `请勾选要删除的数据`, status: 'warning' });
    return;
  }
  const type = await VXETable.modal.confirm('您确定要删除吗？');
  if (type != 'cancel') {
    for (const item of selectRows) {
      for (let i = intfMainList.length - 1; i >= 0; i--) {
        if (item.code == intfMainList[i].code) {
          intfMainList.splice(i, 1);
          break;
        }
      }
    }
    saveList();
  }
}
// 点击行
function moduleRowClick({ row, rowIndex }) {
  leftpane.value = '25';
  rightpane.value = '75';
}
</script>
<style lang="scss" scoped>
#intfconfig {
  .el-form-item {
    margin-right: 10px;
  }
  .el-tabs {
    margin-left: 10px;
  }
  .el-select {
    width: 100%;
  }
  .el-input-number {
    width: 100%;
  }
}
</style>
